package logic

import (
	"bluebell/dao/mysql"
	"bluebell/dao/redis"
	"bluebell/models"
	"bluebell/pkg/snowflake"
	"fmt"
)

func CreatePost(param *models.Post) (err error) {
	param.ID = snowflake.GenID()
	if err = redis.CreatePost(param.ID, param.CommunityID); err != nil {
		return
	}
	return mysql.CreatePost(param)
}

func GetPostDetail(id int64) (post *models.Post, err error) {
	return mysql.GenPostById(id)
}

func GetPostList(page, limit int64) (posts []*models.Post, err error) {
	return mysql.GenPostList(page, limit)
}

func GetPostListByFactor(param *models.ParamPostList) (data []*models.ResPostDetail, err error) {
	var ids []string
	ids, err = redis.GetPostIdsInOrder(param) // 获取符合条件的id合集(切片)
	var posts []*models.Post
	posts, err = mysql.GenPostListByIds(ids) // 根据id合集查询对应的数据库信息
	if err != nil {
		fmt.Println("服务器繁忙")
	}
	var voteData []int64
	voteData, err = redis.GetPostVoteData(ids) // 根据id合集查询赞同数合集(保持ids排序)
	if err != nil {
		fmt.Println("服务器存储超时")
	}
	for idx, post := range posts {
		// 查询作者信息
		var user = new(models.User)
		user, err = mysql.GenUserById(post.AuthorID)

		// 赋值返回数据
		dataDetail := &models.ResPostDetail{
			AuthorName: user.Phone,
			VoteNum:    voteData[idx],
			Post:       post,
		}
		data = append(data, dataDetail)
	}
	return
}

func GetCommunityPostList(param *models.ParamCommunityPostList) (data []*models.ResPostDetail, err error) {
	var ids []string
	ids, err = redis.GetCommunityPostIdsInOrder(param)
	var posts []*models.Post
	posts, err = mysql.GenPostListByIds(ids)
	if err != nil {
		fmt.Println("服务器繁忙")
	}
	var voteData []int64
	voteData, err = redis.GetPostVoteData(ids)
	if err != nil {
		fmt.Println("服务器存储超时")
	}
	for idx, post := range posts {
		// 查询作者信息
		var user = new(models.User)
		user, err = mysql.GenUserById(post.AuthorID)

		// 赋值返回数据
		dataDetail := &models.ResPostDetail{
			AuthorName: user.Phone,
			VoteNum:    voteData[idx],
			Post:       post,
		}
		data = append(data, dataDetail)
	}
	return
}
